package filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest res = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        res.setCharacterEncoding("utf-8");
        String url = res.getRequestURI();
        Object username = res.getSession().getAttribute("username");
        if(url.endsWith("success.jsp")&&username == null){
            res.setAttribute("msg","请先登录");
            res.getRequestDispatcher("/index.jsp").forward(res,resp);
        }
        chain.doFilter(request,response);//调取下一个过滤器，或者servlet

    }

    @Override
    public void destroy() {
        System.out.println("过滤器销毁");
    }
}
